<template>
  <div>
      <span style="cursor: pointer;" @click="changeState"><i class="el-icon-microphone" />{{state}}</span>
  </div>
</template>

<script>
import { ListenUtils } from '@/utils/listen-utils'

export default {
    data() {
        return {
            v: '',
            utils: null,
            state: '开始'
        }
    },

    props: {
        value: String,
    },

    model: {
        prop: 'value',
        event: 'change'
    },

    methods: {
        onResult(res) {
            
            if (res && res.results && res.results.length >= 1 ) {
                res = res.results[0]
                if (res && res.length >= 1) {
                    res = res[0].transcript
                    if (res.length > 1) {
                        res = res.slice(0, res.length - 1)
                    }
                }
                else{
                    res = '请重试'
                }
            }
            else {
                res = '请重试'
            }
            // console.log(res)
            this.$emit('change', res)
            this.$emit('update:value', res)
        },
        changeState() {
            if (!this.utils) {
                this.utils = new ListenUtils(this.onResult)
            }
            if(this.utils.state) {
                this.utils.stop()
                this.state = '结束！'
                setTimeout(() => {
                    this.state = '开始'
                }, 500)
            }
            else{
                this.utils.start()
                this.state = '聆听中...'
                
            }
        }
    },

    mounted() {
        this.utils = new ListenUtils(this.onResult)
    }
}
</script>

<style>

</style>